<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="专利名称" prop="patentTitle">
        <el-input
            v-model="queryParams.patentTitle"
            placeholder="请输入专利名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="专利类型" prop="patentType">
        <el-select v-model="queryParams.patentType" placeholder="请选择专利类型" clearable>
          <el-option label="发明" value="发明" />
          <el-option label="实用新型" value="实用新型" />
          <el-option label="外观设计" value="外观设计" />
          <el-option label="国际专利" value="国际专利" />
        </el-select>
      </el-form-item>
      <el-form-item label="专利状态" prop="patentStatus">
        <el-select v-model="queryParams.patentStatus" placeholder="请选择专利状态" clearable>
          <el-option label="已授权" value="已授权" />
          <el-option label="已受理" value="已受理" />
          <el-option label="已申请" value="已申请" />
        </el-select>
      </el-form-item>
      <el-form-item label="本人排名" prop="authorRank">
        <el-input-number
            v-model="queryParams.authorRank"
            placeholder="本人排名"
            :min="1"
            :max="50"
            controls-position="right"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出</el-button>
      </el-form-item>
    </el-form>



    <el-table v-loading="loading" :data="patentsList" @selection-change="handleSelectionChange" ref="patentTable">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="上传者" align="center" prop="nickName" />
      <el-table-column label="专利名称" align="center" prop="title" />
      <el-table-column label="专利类型" align="center" prop="patentType" />
      <el-table-column label="授权公告日" align="center" prop="authorizationDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.authorizationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="专利申请日" align="center" prop="applicationDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applicationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本人排名" align="center" prop="authorRank" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Download"
              @click="download(scope.row)"
              :disabled="!scope.row.pdfUrl"
          >下载</el-button>
          <el-button
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['result:patents:edit']"
          >详情</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />



    <patent-export v-model="showExportDialog" :papers="exportData" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { treeselect } from "@/api/system/dept";
import PatentExport from "@/components/result/ExportDialog/patentExport.vue";
import { listPatents, getPatents, delPatents, addPatents, updatePatents,getPatentsByIds } from "@/api/result/patents"
import {useRoute, useRouter} from "vue-router";


const router = useRouter()
const route = useRoute()
const queryForm = ref(null)
const form = ref(null)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const open = ref(false)
const patentsList = ref([])
const deptName = ref("");
const deptOptions = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);
const patentTable = ref(null); // 添加 ref 引用
const dateRange = ref(null);
const showExportDialog = ref(false);
const exportData = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  nickName: null,
  patentTitle: null,
  patentType: null,
  patentStatus: null,
  patentNumber: null,
  patentOwner: null,
  authorizationDate: null,
  applicationNumber: null,
  applicationDate: null,
  authorRank: null,
  remarks: null,
  projectId: null,
  authorInfo: null,
  syncStatus: null,
  createdAt: null,
  updatedAt: null,
  pdfUrl: null,
  userId: null,
  queryPublishDate: [],
  deptId: null,
  postIds: [],
  roleIds: [],
})


const download = (row) => {
  if (row.pdfUrl) {
    console.log('下载:', row.pdfUrl);
    window.open(row.pdfUrl, '_blank');
  } else {
    ElMessage.warning('该报告没有可下载的PDF文件');
  }
};
onMounted(() => {

  getList()
})
/** 查询系部下拉树结构 */
function getDeptTree() {
  treeselect().then(response => {
    deptOptions.value = response.data;
  });
  // deptTreeSelect().then(response => {
  //   deptOptions.value = response.data;
  // });
};
/** 查询专利信息列表 */
function getList() {
  loading.value = true
  listPatents(queryParams).then(response => {
    patentsList.value = response.rows
    total.value = response.total
    loading.value = false
    console.log("patentsList.value ",patentsList.value )
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    patentTitle: null,
    patentType: null,
    patentStatus: "0",
    patentNumber: null,
    patentOwner: null,
    authorizationDate: null,
    applicationNumber: null,
    applicationDate: null,
    authorRank: null,
    remarks: null,
    projectId: null,
    authorInfo: null,
    syncStatus: "0",
    createdAt: null,
    updatedAt: null,
    pdfUrl: null,
    userId: null
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryForm.value.resetFields()
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加专利信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log('编辑:', row.id);
  router.push({ path: '/result/patents/edit', query: { id: row.id } });
  // reset()
  // const id = row.id || ids.value
  // getPatents(id).then(response => {
  //   form.value = response.data
  //   open.value = true
  //   title.value = "修改专利信息"
  // })
}

/** 提交按钮 */
function submitForm() {
  form.value.validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePatents(form.value).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPatents(form.value).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const patentIds = row.id || ids.value
  ElMessageBox.confirm('是否确认删除专利信息编号为"' + patentIds + '"的数据项？').then(() => {
    return delPatents(patentIds)
  }).then(() => {
    getList()
    ElMessage.success("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
async function handleExport() {
  if (!patentTable.value) {
    ElMessage.warning('表格未加载，请稍后再试');
    return;
  }

  const selectedRows = patentTable.value.getSelectionRows();
  if (selectedRows.length === 0) {
    ElMessage.warning('请选择要导出的专利');
    return;
  }

  // 提取选中专利的 id
  const selectedIds = selectedRows.map(item => item.id);

  // 获得具体信息
  const res = await getPatentsByIds(selectedIds);

  if (res.code === 200 && res.data) {
    // 打开导出对话框并传递数据
    showExportDialog.value = true;
    // 假设我们添加了一个 exportData ref 来存储要导出的数据
    exportData.value = res.data;
  } else {
    ElMessage.error('获取专利数据失败');
  }
}


</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
